package com.snake.springboot.authority.service.impl;

import com.snake.springboot.authority.api.model.AccountInfoModel;
import com.snake.springboot.authority.api.model.CacheRewriteCommand;
import com.snake.springboot.authority.api.model.RequestUrlModel;
import com.snake.springboot.authority.api.service.AuthUsedService;
import com.snake.springboot.authority.dao.mybatis.entity.RequestUrlDO;
import com.snake.springboot.authority.dao.mybatis.mappers.AuthUsedMapper;
import com.snake.springboot.authority.service.config.AuthProperties;
import com.snake.springboot.authority.service.event.AccountIdentifyEvent;
import com.snake.springboot.authority.service.mq.MqSender;
import org.snake.common.utils.JsonUtils;
import org.snake.common.utils.ListUtils;
import org.snake.redis.commons.RedisPlusUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AuthUsedServiceImpl implements AuthUsedService {
    @Resource
    private AuthUsedMapper authUsedMapper;
    @Resource
    private RedisPlusUtils redisPlusUtils;
    @Resource
    private AuthProperties authProperties;
    @Resource
    private MqSender mqSender;
    @Resource
    private ApplicationContext applicationContext;


    @Override
    public List<RequestUrlModel> requestUrl(Integer whitelistFlag) {
        List<RequestUrlDO> ruleList = authUsedMapper.findRuleList(whitelistFlag);
        List<RequestUrlModel> urlModels = ListUtils.copy(ruleList, RequestUrlModel.class);
        return urlModels;
    }


    @Override
    public AccountInfoModel accountAuth(Integer type, String accountId) {
        String cacheKey = authProperties.getCache() + accountId;
        String cacheVal = redisPlusUtils.getOpsVal(cacheKey, String.class);
        if (cacheVal != null) {
            return JsonUtils.fromJson(cacheVal, AccountInfoModel.class);
        }
        AccountIdentifyEvent event=new AccountIdentifyEvent(this,accountId,type);
        applicationContext.publishEvent(event);
        AccountInfoModel info =event.getResult();
        //写进缓存
        if (info != null) {
            //获取个人权限码
            if (info.getPerms() == null|| info.getPerms().isEmpty()){
                info.setPerms(authUsedMapper.queryPerms(accountId));
            }
            redisPlusUtils.setOpsVal(cacheKey, JsonUtils.toJson(info),3000);
        }
        return info;
    }


    @Override
    public void delCache(AccountInfoModel accountInfo) {
        String cache = authProperties.getCache();
        redisPlusUtils.delKey(cache+accountInfo.getAccountId());
    }

    @Override
    public void refreshRoleCache() {
        CacheRewriteCommand command = new CacheRewriteCommand(CacheRewriteCommand.actionType.roleType);
        String msg = JsonUtils.toJson(command);
        mqSender.sendMsg(authProperties.getGatewayMqExchange(),authProperties.getGatewayMqRoutingKey(),msg);
    }



}
